//
//  AudioPlayerVC.m
//  AVFoundationDemo
//
//  Created by rubick on 2019/1/17.
//  Copyright © 2019 LG. All rights reserved.
//

#import "AudioPlayerVC.h"
#import <AVFoundation/AVFoundation.h>
#import "THPlayerController.h"

@interface AudioPlayerVC ()

@property (weak, nonatomic) IBOutlet UISlider *soundSlider;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (strong, nonatomic) AVAudioPlayer *musicPlayer;
@property (strong, nonatomic) NSTimer *myTimer;

@property (strong, nonatomic) THPlayerController *player;

@end

@implementation AudioPlayerVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Canon" ofType:@"mp3"];
    NSError *error = nil;
    _musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:&error];
    self.musicPlayer.volume = 0.5;
    [_musicPlayer prepareToPlay];
    self.progressSlider.maximumValue = _musicPlayer.duration;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"***" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnItemAction:)];
}
- (void)viewWillDisappear:(BOOL)animated {
    if(self.player) {
        [self.player stop];
    }
    if(self.musicPlayer) {
        [self.musicPlayer stop];
    }
}
- (void)rightBtnItemAction:(id)sender {
    if(self.musicPlayer) {
        [self.musicPlayer stop];
    }
    if(self.player) {
        [self.player stop];
    } else {
        self.player = [[THPlayerController alloc] init];
        [_player play];        
    }
}
- (void)change:(NSTimer *)sender {
    self.progressSlider.value = _musicPlayer.currentTime;
}
- (IBAction)playAction:(id)sender {
    [self.musicPlayer play];
    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(change:) userInfo:nil repeats:YES];
}
- (IBAction)pasureAction:(id)sender {
    [self.musicPlayer pause];
    [self.myTimer invalidate];
}
- (IBAction)soundSliderAction:(id)sender {
    self.musicPlayer.volume = [(UISlider *)sender value];
}
- (IBAction)progressSliderAction:(id)sender {
    self.musicPlayer.currentTime = [(UISlider *)sender value];
}


@end
